<?php
/**
 * This resource gets the campaigns for a given account.
 *
 * PHP version 5
 *
 * Copyright 2011, Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package    SampleWebapp
 * @copyright  2011, Google Inc. All Rights Reserved.
 * @license    http://www.apache.org/licenses/LICENSE-2.0 Apache License,
 *             Version 2.0
 * @author     Eric Koleda <api.ekoleda@gmail.com>
 * @author     Paul Matthews <pmatthews@google.com>
 */

require_once dirname(dirname(__FILE__)) . '/init.php';

// Create result object.
$result = array();

try {
  // Read parameters from the request.
  $customerId = !empty($_REQUEST['customerId']) ? $_REQUEST['customerId']
    : NULL;
  $status = !empty($_REQUEST['status']) ? $_REQUEST['status'] : NULL;

  // Retrieve the AdWordsUser from session.
  $user = SessionManager::GetAdWordsUser();
  $user->SetClientId($customerId);

  // Get the CampaignService.
  $campaignService = $user->GetService('CampaignService', ADWORDS_VERSION);

  // Create selector.
  $selector = new Selector();
  $selector->fields = array(
    'Id', 'Name', 'Status', 'ServingStatus',
    'StartDate', 'EndDate', 'Amount'
  );

  if (isset($status)) {
    $selector->predicates[] = new Predicate('Status', 'IN', array($status));
  }

  // Get all campaigns.
  $page = $campaignService->get($selector);
  $result['campaigns'] = $page->entries;
} catch (Exception $e) {
  $result['error'] = $e->getMessage();
}

// Return results as JSON.
header('Content-Type: text/javascript; charset=utf8');
print json_encode($result);
